<?php

namespace app\common\service\wps;

use app\common\model\Attachment;
use app\common\model\Template;
use think\exception\HttpResponseException;
use think\helper\Str;

class WpsService
{
    protected $appid;
    protected $appkey;
    protected $type;
    protected $fileid;

    public function __construct()
    {
        $this->appid = "4ae85b70be084b20912a325d5a5602b9";
        $this->appkey = "3e8fd3e895bd45b09f7900d6e9a1e7db";
    }

    //新建文件
    public function create($file_name,$file_type,$task_id = 0)
    {
        $file_id = "f" . session("admin.id") ."a". md5(Str::random(6).time());
        Attachment::create([
            "file_name" =>   $file_name,
            "file_type" => $file_type,
            "file_id" => $file_id,
            "task_id" => $task_id,
            "creator" => session("admin.id")
        ]);
        $baseUri = "https://wwo.wps.cn/office/";
        $baseUri .= "{$file_type}/new/";
        $baseUri .= "{$file_id}?";
        $baseUri .= "_w_appid=" . $this->appid;
        $baseUri .= "&_w_userid=" . session("admin.id");
        $baseUri .= "&_w_signature=" . $this->makeSign([
                "_w_userid"=>session('admin.id'),
                '_w_appid'=>$this->appid
            ]);
        return $baseUri;
    }

    public function makeUri($file_id,$file_type,$param)
    {
        $param['_w_appid'] = $this->appid;
        $baseUri = "https://wwo.wps.cn/office/";
        $baseUri .= "{$file_type}/";
        $baseUri .= "{$file_id}?";
        foreach ($param as $key=>$value) {
            $baseUri .= "$key=" . $value . "&";
        }
        $baseUri .= "_w_signature=" . $this->makeSign($param);
        return $baseUri;
    }

    public function makeTemplateUri($file_id,$param = []) {
        $file = Template::where("file_id",$file_id)->find();
        if (!$file || !file_exists(ltrim($file->path,"/"))) {
            throwError('文件不存在');
        }
        $param = array_merge($param,['_w_appid'=>$this->appid]);
        $baseUri = "https://wwo.wps.cn/office/";
        $baseUri .= "{$file->file_type}/";
        $baseUri .= "{$file_id}?";
        foreach ($param as $key=>$value) {
            $baseUri .= "$key=" . $value . "&";
        }
        $baseUri .= "_w_signature=" . $this->makeSign($param);
        return $baseUri;
    }

    public function makeSign($param) {
        ksort($param);
        $content = "";
        foreach ($param as $key=>$value) {
            $content .= $key . "=" . $value;
        }
        $content .= "_w_secretkey=" . $this->appkey;
        $sign = base64_encode(hash_hmac('sha1',$content,$this->appkey,true));
        return urlencode($sign);
    }
}